<template>
  <div>
    <div ref="gantt" class="gantt" :style="{height: propsData.isProject ? '66vh' : '76vh'}" /> 
  </div>
</template>
  
<script>
import gantt from "dhtmlx-gantt";
import "dhtmlx-gantt/codebase/ext/dhtmlxgantt_marker.js"; //标识线
import "dhtmlx-gantt/codebase/dhtmlxgantt.css";
import "dhtmlx-gantt/codebase/skins/dhtmlxgantt_terrace.css"; //皮肤
import "dhtmlx-gantt/codebase/locale/locale_cn"; // 本地化
import "dhtmlx-gantt/codebase/ext/dhtmlxgantt_tooltip.js"; //任务栏悬浮显示
import moment from "moment";

export default {
  props: {
    propsData: {
      type: Object,
      default: () => {},
    },
    viewFormat:{
      type: String,
      default: 'day',
    }
  },
  watch: {
    "propsData.list": {
      async handler(newName, oldName) {
        const list = JSON.parse(JSON.stringify(this.propsData.list));
        list.forEach((item) => {
          item.text = item.type;
          item.open = true;
          item.color = "#409eff";
          if (item.tasks.length) {
            item.tasks.forEach((val) => {
              val.text = val.title;
              val.open = true;
              if (val.priority === "2") {
                val.color = "#e6a23c";
              } else if (val.priority === "3") {
                val.color = "#ff4949";
              } else {
                val.color = "#409eff";
              }
              if (val.startTime) {
                val.start_date = val.startTime;
              }
              if (val.endTime) {
                val.end_date = val.endTime;
              }
              if (!val.superiorTaskId) {
                if (item.id === "0") {
                  val.parent = "noId0";
                  item.id = "noId0";
                } else {
                  val.parent = item.id;
                }
              } else {
                val.parent = val.superiorTaskId;
              }
            });
          }
        });
        const listData = [];
        list.forEach((item) => {
          listData.push(item);
          if (item.tasks?.length) {
            listData.push(...item.tasks);
          }
        });
        this.tableData = listData;
        await this.loadData();
      },
      immediate: true,
    },
    "propsData.viewList": {
      async handler(newName, oldName) {
        const list = [];
        this.propsData?.list?.forEach((item) => {
          if (
            this.propsData.viewList?.includes(item.type) ||
            !this.propsData.viewList?.length
          )
            list.push({ ...item, title: item.type });
        });
        list?.forEach((item) => {
          if (
            this.propsData.viewList?.includes(item.type) ||
            !this.propsData.viewList?.length
          ) {
            item.text = item.type;
            item.open = true;
            item.color = "#409eff";
            if (item.tasks.length) {
              item.tasks.forEach((val) => {
                val.text = val.title;
                val.open = true;
                if (val.priority === "2") {
                  val.color = "#e6a23c";
                } else if (val.priority === "3") {
                  val.color = "#ff4949";
                } else {
                  val.color = "#409eff";
                }
                if (val.startTime) {
                  val.start_date = val.startTime;
                }
                if (val.endTime) {
                  val.end_date = val.endTime;
                }
                if (!val.superiorTaskId) {
                  if (item.id === "0") {
                    val.parent = "noId0";
                    item.id = "noId0";
                  } else {
                    val.parent = item.id;
                  }
                } else {
                  val.parent = val.superiorTaskId;
                }
              });
            }
          }
        });
        const listData = [];
        list.forEach((item) => {
          listData.push(item);
          if (item.tasks?.length) {
            listData.push(...item.tasks);
          }
        });
        this.tableData = listData;
        await this.loadData();
      },
      immediate: true,
    },
  },
  data() {
    return {
      tableData: [],
    };
  },
  mounted() {},
  methods: {
    // 初始化
    init() {
      gantt.addMarker({
        start_date: new Date(),
        css: "today", //today样式class为自带，其他的时间标识线需要自己定义class
        text: "今天",
        title: "今天: ",
      });
      (gantt.templates.task_text = function (start, end, task) {
        return `${task.text} (${moment(start).format(
          "YYYY-MM-DD HH:mm:ss"
        )} - ${moment(end).format("YYYY-MM-DD HH:mm:ss")})`;
      }),
        // 格式化日期
        (gantt.locale.date = {
          month_full: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          month_short: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          day_full: [
            "星期日",
            "星期一",
            "星期二",
            "星期三",
            "星期四",
            "星期五",
            "星期六",
          ],
          day_short: [
            "星期日",
            "星期一",
            "星期二",
            "星期三",
            "星期四",
            "星期五",
            "星期六",
          ],
        });

      gantt.locale.labels = {
        dhx_cal_today_button: "今天",
        day_tab: "日",
        week_tab: "周",
        month_tab: "月",
        minutes: "分钟",
        hours: "小时",
        days: "天",
        weeks: "周",
        months: "月",
        years: "年",
      };
      gantt.config.date_format = "%Y-%m-%d";
      //自适应甘特图的尺寸大小, 使得在不出现滚动条的情况下, 显示全部任务
      gantt.config.autosize = false;
      //只读模式
      gantt.config.readonly = true;
      //是否显示左侧树表格
      gantt.config.show_grid = true;
      // //表格列设置
      gantt.config.columns = [
        {
          name: "text",
          label: "任务标题",
          tree: true,
          width: "250",
          align: "left",
        },
        {
          name: "status",
          label: "任务状态",
          width: "150",
          align: "center",
          template: function (obj) {
            const statusEnmu = {
              0: "处理中",
              10: "完成待审批",
              20: "审批中",
              30: "审批不通过",
              40: "已完成",
            };
            return statusEnmu[obj.status];
          },
        },
        {
          name: "priority",
          label: "优先级",
          width: "100",
          align: "center",
          template: function (obj) {
            const priorityEnmu = {
              1: "普通",
              2: "紧急",
              3: "非常紧急",
            };
            return priorityEnmu[obj.priority];
          },
        },
        {
          name: "startTime",
          label: "开始时间",
          width: "150",
          align: "center",
        },
        {
          name: "endTime",
          label: "结束时间",
          width: "150",
          align: "center",
        },
      ];
      // 自动延长时间刻度
      gantt.config.fit_tasks = true;
      // 允许拖放
      gantt.config.drag_project = false;
      // 定义时间格式
      gantt.config.min_column_width = 120;
      // gantt.config.scale_unit = "year";
      // gantt.config.date_scale = "%Y年";
      //      gantt.config.scale_unit = "month";
      // gantt.config.date_scale = "%Y年 - %F";
      // gantt.config.scale_unit = "day";
      // gantt.config.date_scale = "%Y年%F%j日";
      // gantt.config.scales = [
      //   { unit: "month", step: 1, date: " %Y-%F" },
      //   { unit: "day", step: 1, date: " %j (%D)" },
      // ];
      // gantt.config.start_date = new Date('2024,01, 01'),
      // gantt.config.end_date = new Date('2049, 10, 01'),
      const viewFormatObj = {
        // hour: [
        //   { unit: "month", step: 1, date: "%Y年%m月" },
        //   { unit: "day", step: 1, date: "%d日" },
        //   { unit: "day", step: 1, date: "%D" },
        //   { unit: "hour", step: 1, format: "%H" },
        // ],
        day: [
          { unit: "month", step: 1, date: "%Y年%m月" },
          { unit: "day", step: 1, date: "%d日" },
          { unit: "day", step: 1, date: "%D" },
        ],
        month: [
          { unit: "year", step: 1, date: "%Y年" },
          { unit: "month", step: 1, date: "%Y年%m月" },
        ],
        year: [{ unit: "year", step: 1, date: "%Y年" }],
      };
      gantt.config.scales = viewFormatObj[this.viewFormat];

      // //当task的长度改变时，自动调整图表坐标轴区间用于适配task的长度
      gantt.config.fit_tasks = true;
      gantt.config.initial_scroll = true;
      gantt.config.scale_height = 80;
      gantt.config.show_progress = false;
      gantt.config.show_unscheduled = true;

      gantt.templates.tooltip_text = function (start, end, task) {
        const statusEnmu = {
              0: "处理中",
              10: "完成待审批",
              20: "审批中",
              30: "审批不通过",
              40: "已完成",
            };
            const priorityEnmu = {
              1: "普通",
              2: "紧急",
              3: "非常紧急",
            };
        return `
            <div style='display:flex;flex-wrap:wrap;align-items: center;font-size:12px;width:500px;overflow:hidden'>
              <div style='width: 50%;line-height: 18px;'>任务标题：${
                task.text || "--"
              }</div>
              <div style='width: 50%;line-height: 18px;'>状态：${statusEnmu[task.status]
                || "--"
              }</div>
              <div style='width: 50%;line-height: 18px;'>优先级：${priorityEnmu[task.priority]
                 || "--"
              }</div>
              <div style='width: 50%;line-height: 18px;'>负责人：${
                task.headUserName || "--"
              }</div>
             
              <div style='width: 50%;line-height: 18px;'>开始日期：${
                task.startTime || "--"
              }</div>
              <div style='width: 50%;line-height: 18px;'>结束日期：${
                task.endTime || "--"
              }</div>
            </div>
            `;
      };
      // 初始化
      gantt.init(this.$refs.gantt);
      /* *******重点******* */
      gantt.clearAll(); // 清空旧数据
      /* ****************** */
      // 数据解析
      gantt.parse({ data: this.tableData });
    },
    async loadData() {
      const _this = this;
      this.$nextTick(() => {
        _this.init();
      });
    },
    convertToTree(data, id) {
      const tree = [];
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const parentId = node.superiorTaskId;
        if (!parentId) {
          tree.push(node);
          continue;
        }
        for (let j = 0; j < data.length; j++) {
          const parentNode = data[j];
          if (parentNode.id === parentId) {
            if (!parentNode.tasks) {
              parentNode.tasks = [];
            }
            parentNode.tasks.push({ ...node });
            // parentNode.parent = id
            break;
          }
        }
      }
      return tree;
    },
    addParentId(nodes, parentId = null) {
      nodes.forEach((node) => {
        node.text = node.title;
        node.open = true;
        if (node.priority === "2") {
          node.color = "#e6a23c";
        } else if (node.priority === "3") {
          node.color = "#ff4949";
        } else {
          node.color = "#409eff";
        }
        if (node.startTime) {
          node.start_date = node.startTime;
        }
        if (node.endTime) {
          node.end_date = node.endTime;
        }
        if (node.tasks && node.tasks.length > 0) {
          node.tasks.forEach((child) => {
            child.parent = node.id;

            this.addParentId([child], child.parentId);
          });
        }
      });
    },
    terrOrList(source) {
      let res = [];
      source.forEach((el) => {
        const obj = { ...el, text: el.title, open: true };
        if (el.priority === "2") {
          obj.color = "#e6a23c";
        } else if (el.priority === "3") {
          obj.color = "#ff4949";
        } else {
          obj.color = "#409eff";
        }
        if (el.startTime) {
          obj.start_date = el.startTime;
        }
        if (el.endTime) {
          obj.end_date = el.endTime;
        }
        res.push(obj);
        el.tasks && res.push(...this.terrOrList(el.tasks));
      });
      return res;
    },
  },
};
</script>
  
<style lang="less" scoped>
::v-deep .gantt_task_content {
  // font-weight: bold;
  font-size: 12px;
  text-align: left !important;
  padding-left: 12px;
  border: none;
  box-shadow: none;
}
::v-deep .gantt_task_line {
   border: none;
  box-shadow: none;
  border-radius: 20px;
}
::v-deep .gantt_grid_head_cell {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}
::v-deep .gantt_scale_cell {
   color: #333 !important;
  font-weight: bold;
}
.secondLevelTask {
  border: none;
}

.thirdLevelTask {
  border: 2px solid #da645d;
  color: #da645d;
  background: #da645d;
}

.milestone-default {
  border: none;
  background: rgba(0, 0, 0, 0.45);
}

.milestone-unfinished {
  border: none;
  background: #5692f0;
}

.milestone-finished {
  border: none;
  background: #84bd54;
}

.milestone-canceled {
  border: none;
  background: #da645d;
}

html,
body {
  margin: 0px;
  padding: 0px;
  height: 100%;
  overflow: hidden;
}

.container {
  height: 900px;

  .left-container {
    height: 100%;
  }
}

.left-container {
  height: 600px;
}

.gantt_scale_line {
  border-top: 0;
}

.weekend {
  //background:#f4f7f4!important;
  color: #000000 !important;
}

.gantt_selected .weekend {
  background: #f7eb91 !important;
}

.gantt_task_content {
  text-align: left;
  padding-left: 10px;
}

//上面任务条样式
.gantt_task_scale {
  height: 45px !important;
}

.gantt_task .gantt_task_scale .gantt_scale_cell {
  line-height: 30px !important;
  height: 28px !important;
}
</style>
  